package com.mineoj.controller;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mineoj.annotation.AuthCheck;
import com.mineoj.common.BaseResponse;
import com.mineoj.common.DeleteRequest;
import com.mineoj.common.ErrorCode;
import com.mineoj.common.ResultUtils;
import com.mineoj.constant.UserConstant;
import com.mineoj.exception.BusinessException;
import com.mineoj.exception.ThrowUtils;
import com.mineoj.model.dto.question.JudgeCase;
import com.mineoj.model.dto.question.JudgeConfig;
import com.mineoj.model.dto.solution.*;
import com.mineoj.model.entity.Solution;
import com.mineoj.model.entity.User;
import com.mineoj.model.vo.SolutionVO;
import com.mineoj.service.SolutionService;
import com.mineoj.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 题解接口
 *
 
 */
@RestController
@RequestMapping("/solution")
@Slf4j
public class SolutionController {

    @Resource
    private SolutionService solutionService;

    @Resource
    private UserService userService;

    // region 增删改查

    /**
     * 创建
     *
     * @param solutionAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addSolution(@RequestBody SolutionAddRequest solutionAddRequest, HttpServletRequest request) {
        if (solutionAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        // 登录才能提交题解
        final User loginUser = userService.getLoginUser(request);
        long solutionId = solutionService.doSolution(solutionAddRequest, loginUser);

        return ResultUtils.success(solutionId);
    }

    /**
     * 删除
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteSolution(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        Solution oldSolution = solutionService.getById(id);
        ThrowUtils.throwIf(oldSolution == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldSolution.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }

        boolean b = solutionService.deleteById(id);
        return ResultUtils.success(b);
    }
    

    /**
     * 根据 id 获取
     *
     * @param id
     * @return SolutionVO
     */
    @GetMapping("/get/vo")
    public BaseResponse<SolutionVO> getSolutionVOById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Solution solution = solutionService.getById(id);
        if (solution == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return ResultUtils.success(solutionService.getSolutionVO(solution, request));
    }

    /**
     * 分页获取题解列表
     *
     * @param solutionQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Solution>> listSolutionByPage(@RequestBody SolutionQueryRequest solutionQueryRequest,
                                                           HttpServletRequest request) {
        long current = solutionQueryRequest.getCurrent();
        long size = solutionQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Solution> solutionPage = solutionService.page(new Page<>(current, size),
                solutionService.getQueryWrapper(solutionQueryRequest));
        return ResultUtils.success(solutionPage);
    }
    

    /**
     * 分页获取当前用户创建的资源列表
     *
     * @param solutionQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page")
    public BaseResponse<Page<SolutionVO>> listMySolutionByPage(@RequestBody SolutionQueryRequest solutionQueryRequest,
            HttpServletRequest request) {
        if (solutionQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        solutionQueryRequest.setUserId(loginUser.getId());
        long current = solutionQueryRequest.getCurrent();
        long size = solutionQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Solution> solutionPage = solutionService.page(new Page<>(current, size),
                solutionService.getQueryWrapper(solutionQueryRequest));
        return ResultUtils.success(solutionService.getSolutionVOPage(solutionPage, request));
    }

    /**
     * 编辑（用户）
     *
     * @param solutionEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editSolution(@RequestBody SolutionEditRequest solutionEditRequest, HttpServletRequest request) {
        if (solutionEditRequest == null || solutionEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Solution solution = new Solution();
        BeanUtils.copyProperties(solutionEditRequest, solution);

        // 参数校验
        solutionService.validSolution(solution, false);
        User loginUser = userService.getLoginUser(request);
        long id = solutionEditRequest.getId();
        // 判断是否存在
        Solution oldSolution = solutionService.getById(id);
        ThrowUtils.throwIf(oldSolution == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldSolution.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean result = solutionService.updateById(solution);
        return ResultUtils.success(result);
    }

}
